import React from 'react';
import {
  Table,
  Button,
  Tag,
  Input,
  DatePicker,
  Form,
  message,
  Modal,
  Select,
  Calendar,
  Row,
  Col,
} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import FirstComponent from './FirstComponent';
import moment from 'moment';
import Editer from './Editer';
import { userId } from '@/constant';
import Global from '@/components/Global'
const creator = (type, payload) => ({ type, payload });
const { Option } = Select;

const weatherArr = ['多云', '晴天', '阴天'];
const { TextArea } = Input;
class Diary extends React.Component {
  constructor(props) {
    super(props);
    // this.myChild = React.createRef();
    this.state = {
      diaryVisible: false,
      date: '', //选中的日期
      weather: '',
      type: '', //新增或修改
      _id:'',//要修改的数据
      date1: [
        { date: '2020-03-22', id: 1 },
        { date: '2020-03-23', id: 2 },
        { date: '2020-03-24', id: 3 },
      ],
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    //获取该用户所有日记
    let id = window.sessionStorage.getItem(userId);
    dispatch(creator('diary/getDiary',{id,date:'all'}));
  }
  openDiary = () => {
    this.setState({
      diaryVisible: true,
    });
  };
  //日记确认
  handleOk = () => {
    const { dispatch, form } = this.props;
    const {title}=this.state;
    let obj = {
      date: moment(this.state.date).format('YYYY-MM-DD'),
      weather: form.getFieldValue('weather'),
      content: this.myChild.editor.txt.html(),
    };
    if(title==='新增'){
      obj.id=window.sessionStorage.getItem(userId)
      dispatch(creator('diary/writeDiary', obj)).then(res => {
        if (res.httpStatus === 200) {
           let id = window.sessionStorage.getItem(userId);
    dispatch(creator('diary/getDiary',{id,date:'all'}));
        }
      });
    }else{//修改
      obj['_id']=this.state._id;
      dispatch(creator('diary/update', obj)).then(res => {
        if (res.httpStatus === 200) {
           let id = window.sessionStorage.getItem(userId);
          dispatch(creator('diary/getDiary',{id,date:'all'}));
        }
      });
    }
    this.handleCancel()
  };
  handleCancel = () => {
    this.setState({
      diaryVisible: false,
    });
  };

  handleSizeChange = e => {
    this.setState({ size: e.target.value });
  };
  //是否渲染圆点
  dateCellRender = date => {
    const {diaries}=this.props.diary;
    let result = diaries.length&&diaries.find(
      item => moment(item.date).format('YYYY-MM-DD') === moment(date).format('YYYY-MM-DD'),
    );
    if (result && moment(date).format('YYYY-MM-DD') !== moment().format('YYYY-MM-DD')) {
      return (
        <a
          style={{
            display: 'block',
            width: '22px',
            height: '22px',
            lineHeight: '22px',
            color: 'green',
            borderRadius: '50%',
            // background: 'rgb(255,165,0)',
            background: '#1890ff',
            fontSize: 12,
          }}
        >
          &radic;
        </a>
      );
    } else {
      return <a style={{ display: 'block', width: '16px', height: '16px' }}></a>;
    }
  };
  //点击时的回调
  onSelect = date => {
    let id = window.sessionStorage.getItem(userId);
    const { dispatch,form } = this.props;
    date=moment(date).format('YYYY-MM-DD')
    dispatch(creator('diary/getDiary', { id,date  })).then(res => {
      if (res.httpStatus === 200) {
        if (!res.data.length) {
          this.myChild.editor.txt.html('<p><br></p>')
          this.setState({ title: '新增',weather:'多云' });
        }else{
          form.setFieldsValue({weather:res.data[0].weather})

          this.myChild.editor.txt.html(res.data[0].content)
          this.setState({ title: '修改' ,_id:res.data[0]['_id'],weather:res.data[0]['weather']});
        }
      }
      
    });
    this.setState({
      date,
      diaryVisible: true,
    });
  };
 
  //数字转大写
  numberToBig = number => {
    switch (number) {
      case 1:
        return '星期一';
      case 2:
        return '星期二';
      case 3:
        return '星期三';
      case 4:
        return '星期四';
      case 5:
        return '星期五';
      case 6:
        return '星期六';
      case 7:
        return '星期天';
      default:
        return '';
    }
  };
  weatherChange=(weather)=>{
    this.setState({weather})
  }
  render() {
    const { diaries } = this.props.diary;
    const { getFieldDecorator } = this.props.form;
    const title = (
      <Row>
        <Col span={17}>
          <span>{moment(this.state.date).format('YYYY-MM-DD')}</span>&nbsp;
          <span>{this.numberToBig(moment(this.state.date).day())}</span>
        </Col>
        <Col span={5}>
          {getFieldDecorator('weather', {
            initialValue: '多云',
          })(
            <Select style={{ width: 80 }} onChange={this.weatherChange}>
              {weatherArr.map(item => (
                <Option key={item}>{item}</Option>
              ))}
            </Select>,
          )}
        </Col>
      </Row>
    );
    return (
      <div className={styles.wrapper}>
        <Calendar
          fullscreen={false}
          dateCellRender={this.dateCellRender}
          onSelect={this.onSelect}
        />
        <Form layout="inline">
          <Modal
            title={title}
            visible={this.state.diaryVisible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            width={850}
          >
            <Editer onRef={ref => (this.myChild = ref)} weather={this.state.weather} />
          </Modal>
        </Form>
      </div>
    );
  }
}
// defaultPickerValue={moment(new Date(),'YY-MM-DD')-moment(new Date(),'d')}
// export default Plan;

const WrappedDiary = Form.create({ name: 'diary' })(Diary);

export default connect(({ diary }) => ({ diary }))(WrappedDiary);
